package cn.edu.my.directory;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DirectoryManager {
	/**
	 * ɾ���Ŀ¼
	 * 
	 * @param dir
	 *            ��Ҫɾ���Ŀ¼·��
	 */
	private static void doDeleteEmptyDir(String dir) {
		boolean success = (new File(dir)).delete();
		if (success) {
			System.out.println("Successfully deleted empty directory: " + dir);
		} else {
			System.out.println("Failed to delete empty directory: " + dir);
		}
	}

	/**
	 * �ݹ�ɾ��Ŀ¼�µ������ļ�����Ŀ¼�������ļ�
	 * 
	 * @param dir
	 *            ��Ҫɾ����ļ�Ŀ¼
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	private static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			// �ݹ�ɾ��Ŀ¼�е���Ŀ¼��
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// Ŀ¼��ʱΪ�գ�����ɾ��
		return dir.delete();
	}

	private static void printLastModifiedTime() {
		File file = new File("D:\123");
		long time = file.lastModified();// �����ļ�����޸�ʱ�䣬���Ը�long�ͺ�����
		
		System.out.println(time);
		String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
				.format(new Date(time));
		System.out.println(ctime);
	}
	
	private static boolean beyondLimit(File dir){
		Date limitDate=new Date(new Date().getYear(),new Date().getMonth(),new Date().getDate()-7);
		String[] oldDir = dir.list();
		for(int i=0; i<oldDir.length; i++){
			String[] newDir=oldDir[i].split("-bkup-");
			System.out.println(newDir[0]);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
			Date d;
			try {
				d = sdf.parse(newDir[1]);
				boolean flag = d.after(limitDate);
				return flag;
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * ����
	 */
	public static void main(String[] args) {
		boolean success=false;
		File dir=new File("E:\\svn_dump\\ajaf");
        if(beyondLimit(dir)){
        	success=deleteDir(dir);
        }
        
        if (success) {
            System.out.println("Successfully deleted populated directory: " + dir);
        } else {
            System.out.println("Failed to delete populated directory: " + dir);
        } 
        doDeleteEmptyDir(dir.getName());
	}
}
